package bizctx

import (
	"context"
	"gfDemo/internal/consts"
	"gfDemo/internal/model"
	"gfDemo/internal/service"
	"github.com/gogf/gf/v2/net/ghttp"
)

type sBizCtx struct {
}

func init() {
	service.RegisterBizCtx(New())
}

func New() service.IBizCtx {
	return &sBizCtx{}
}

func (s *sBizCtx) Init(r *ghttp.Request) {
	mCtx := &model.Context{
		Session: r.Session,
	}
	r.SetCtxVar(consts.ContextKey, mCtx)
	user := service.Session().GetUser(r.Context())
	if user != nil {
		mCtx.User = &model.ContextUser{
			Id:       user.Id,
			Passport: user.Passport,
			Nickname: user.Nickname,
		}
	}
}

func (s *sBizCtx) Get(ctx context.Context) *model.Context {
	value := ctx.Value(consts.ContextKey)
	if value == nil {
		return nil
	}
	if localCtx, ok := value.(*model.Context); ok {
		return localCtx
	}
	return nil
}

func (s *sBizCtx) SetUser(ctx context.Context, ctxUser *model.ContextUser) {
	biz := s.Get(ctx)
	if biz != nil {
		biz.User = ctxUser
	}
}
